package com.panda.cn.config.aspect;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.panda.cn.config.exception.CustomException;
import com.panda.cn.config.exception.RestfulException;
import com.panda.cn.entity.SysOperLogEntity;
import com.panda.cn.mapper.SysOperLogMapper;
import com.panda.cn.utils.userAgent.UserAgentUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;


/**
 * @author: menghao.yan
 * @create: Created in 2021/2/6
 * @description: 自定义系统日志Syslog注解环绕通知
 */

@Slf4j
@Aspect
@Component
public class SysLogAspect {
    @Resource
    private SysOperLogMapper sysOperLogMapper;
    
    @Pointcut("@annotation(com.panda.cn.config.aspect.OperLog)")
    public void logPointCut() {
    
    }
    
    /**
     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     */
    @Pointcut("execution(* com.panda.cn.controller..*.*(..))")
    public void exceptionLogPointCut() {
    }
    
    @Around(value = "logPointCut()")
    public Object around(ProceedingJoinPoint point) throws RestfulException {
        long beginTime = System.currentTimeMillis();
        //执行方法
        try {
            Object proceed = point.proceed(); // 验证是不是一个对象
            //执行时长(毫秒)
            long time = System.currentTimeMillis() - beginTime;
            aroundLog(point, time, formatProceed(proceed));
            //保存日志
            return proceed;
        } catch (RestfulException e) {
            //执行时长(毫秒)
            long time = System.currentTimeMillis() - beginTime;
            //保存日志
            exceptionLog(point, time, e);
            throw new RestfulException(e.getMessage());
        } catch (Throwable e) {
            //执行时长(毫秒)
            long time = System.currentTimeMillis() - beginTime;
            //保存日志
            exceptionLog(point, time, e);
            throw new CustomException(e.getMessage());
        }
    }
    // 格式化数据
    private String formatProceed(Object proceed) {
        if (ObjUtil.isEmpty(proceed)) {
            return "";
        }
        if (proceed instanceof String || proceed instanceof Double || proceed instanceof Long || proceed instanceof Float || proceed instanceof Integer || proceed instanceof Boolean) {
            return StrUtil.toString(proceed);
        }
        return JSONUtil.toJsonStr(proceed);
    }
    
    private void aroundLog(JoinPoint joinPoint, long time, String proceed) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String requestURI = request.getRequestURI();
        String methodType = request.getMethod();
        String ip = UserAgentUtil.getIp(request);
        String ipAddress = UserAgentUtil.getIpAddress(ip);
        log.info(String.format(">>>  requestURI: %s", requestURI));
        log.info(String.format(">>>  method: %s", methodType));
        log.info(String.format(">>>  ip: %s", ip));
        log.info(String.format(">>>  ipAddress: %s", ipAddress));
        
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        
        OperLog syslog = method.getAnnotation(OperLog.class);
        if (syslog != null) {
            //注解上的描述
            log.info(String.format(">>>  operModul: %s", syslog.operModul()));
            log.info(String.format(">>>  operType:  %s", syslog.operType()));
            log.info(String.format(">>>  operDesc:  %s", syslog.operDesc()));
        }
        
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.info(String.format(">>>  className:  %s", className));
        log.info(String.format(">>>  methodName: %s", methodName));
        
        //请求的参数
        String[] parameterNames = signature.getParameterNames();
        Object[] args = joinPoint.getArgs();
        JSONObject paramJson = new JSONObject();
        for (int i = 0; i < parameterNames.length; i++) {
            paramJson.set(parameterNames[i], args[i]);
        }
        String params = JSONUtil.toJsonStr(paramJson);
        log.info(String.format(">>>  params: %s", params));
        log.info(String.format(">>>  time:   %s ms", time));
        // 存储数据库日志
        SysOperLogEntity operLogEntity = new SysOperLogEntity();
        operLogEntity.setModul(syslog.operModul());
        operLogEntity.setType(syslog.operType());
        operLogEntity.setMessage(syslog.operDesc());
        operLogEntity.setClassName(className);
        operLogEntity.setMethodName(methodName);
        operLogEntity.setParams(params);
        operLogEntity.setTime(time);
        operLogEntity.setStatus("SUCCESS");
        operLogEntity.setResultMessage(proceed);
        operLogEntity.setIp(ip);
        operLogEntity.setIpAddress(ipAddress);
        operLogEntity.setUri(requestURI);
        operLogEntity.setMethodType(methodType);
        // 当前时间
        DateTime nowDateTime = DateUtil.parse(DateUtil.now());
        operLogEntity.setCreateTime(nowDateTime);
        sysOperLogMapper.insert(operLogEntity);
        
    }
    
    private void exceptionLog(JoinPoint joinPoint, long time, Throwable e) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String requestURI = request.getRequestURI();
        String methodType = request.getMethod();
        String ip = UserAgentUtil.getIp(request);
        String ipAddress = UserAgentUtil.getIpAddress(ip);
    
        log.info(String.format(">>>  requestURI: %s", requestURI));
        log.info(String.format(">>>  method: %s", methodType));
        log.info(String.format(">>>  ip: %s", ip));
        log.info(String.format(">>>  ipAddress: %s", ipAddress));
        
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        
        OperLog syslog = method.getAnnotation(OperLog.class);
        if (syslog != null) {
            //注解上的描述
            log.info(String.format(">>>  operModul: %s", syslog.operModul()));
            log.info(String.format(">>>  operType:  %s", syslog.operType()));
            log.info(String.format(">>>  operDesc:  %s", syslog.operDesc()));
        }
        
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.info(String.format(">>>  className:  %s", className));
        log.info(String.format(">>>  methodName: %s", methodName));
        
        //请求的参数
        String[] parameterNames = signature.getParameterNames();
        Object[] args = joinPoint.getArgs();
        JSONObject paramJson = new JSONObject();
        for (int i = 0; i < parameterNames.length; i++) {
            paramJson.set(parameterNames[i], args[i]);
        }
        String params = JSONUtil.toJsonStr(paramJson);
        log.info(String.format(">>>  params: %s", params));
        log.info(String.format(">>>  time:   %s ms", time));
        
        // 异常信息
        String exceptionClassName = e.getClass().getName();
        
        log.error(String.format(">>>  exceptionClassName: %s", exceptionClassName));
        String exceptionTrace = stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace());
        if (!(e instanceof RestfulException)) {
            log.error(String.format(">>>  exceptionTrace: %s", exceptionTrace));
        }
        // 存储数据库日志
        SysOperLogEntity operLogEntity = new SysOperLogEntity();
        operLogEntity.setModul(syslog.operModul());
        operLogEntity.setType(syslog.operType());
        operLogEntity.setMessage(syslog.operDesc());
        operLogEntity.setClassName(className);
        operLogEntity.setMethodName(methodName);
        operLogEntity.setParams(params);
        operLogEntity.setTime(time);
        operLogEntity.setStatus("THROW");
        operLogEntity.setResultMessage(exceptionTrace);
        operLogEntity.setIp(ip);
        operLogEntity.setIpAddress(ipAddress);
        operLogEntity.setUri(requestURI);
        operLogEntity.setMethodType(methodType);
        // 当前时间
        DateTime nowDateTime = DateUtil.parse(DateUtil.now());
        operLogEntity.setCreateTime(nowDateTime);
        sysOperLogMapper.insert(operLogEntity);
        
    }
    
    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuilder strBuff = new StringBuilder();
        for (StackTraceElement stet : elements) {
            strBuff.append(stet).append("\n");
        }
        return exceptionName + ":" + exceptionMessage + "\n\t" + strBuff.toString();
    }
}
